package com.webchat.ugc.service.redpacket;

import com.webchat.common.constants.RedPacketConstants;
import com.webchat.common.enums.RedisKeyEnum;
import com.webchat.common.exception.BusinessException;
import com.webchat.domain.vo.response.RedPacketBaseVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.webchat.common.enums.LUAScriptConstants.OPEN_LUA_SCRIPT;


/**
 * 方案二：自定义lua脚本由redis底层命令单线程执行来保证并发安全
 */
@Service
public class OpenRedPacketWithLuaService extends AbstractOpenRedPacketService {




    @Override
    public int openRedPacket(RedPacketBaseVO redPacket, String userId) {
        Long redPacketId = redPacket.getId();

        List<String> keys = new ArrayList<>();
        // KEY1：红包剩余可拆分金额
        keys.add(RedisKeyEnum.RED_PACKET_BALANCE_COUNT.getKey());
        // KEY2：红包剩余可拆分份额
        keys.add(RedisKeyEnum.RED_PACKET_GRAD_COUNT.getKey());
        // KEY3：红包对应拆分用户名单缓存
        keys.add(RedisKeyEnum.RED_PACKET_OPEN_USERS.getKey(String.valueOf(redPacketId)));

        String amount = redisService.executeScript(
                RedisScript.of(OPEN_LUA_SCRIPT, String.class),
                keys,
                redPacketId, userId);
        if (StringUtils.isBlank(amount)) {
            super.updateRedPacketStatus(redPacketId, RedPacketConstants.RedPacketStatus.END);
            throw new BusinessException("来晚了");
        }
       return Integer.valueOf(amount);
    }
}
